<?php

namespace Common\Logic;

/**
 * 客栈逻辑
 * @modify trainyao 2015-12-31 创建
 */
class HotelLogic extends \Common\Controller\BaseController {

    /**
     * 添加客栈逻辑
     * @modify trainyao 2015-12-31  创建
     * @param  string   $name       客栈名
     * @param  integer   $cityId     城市id
     * @param  integer   $districtId 区id
     * @param  integer   $communityNo 集群号
     * @param  integer   $masterentityId 集群id
     * @param  integer   $currencyId 货币id
     * @modify wenhui 2017-5-12 添加时区
     */
    public function addInfo($name, $cityId, $districtId, $universalTime = '5', $communityNo = null, $masterentityId = null, $currencyId = null) {
        $userId = getUserId();

        $adminLoginModel = D('AdminLogin');
        $adminLoginInfo = $adminLoginModel->getInfo($userId);
        $cityModel = D('City');
        $cityInfo = $cityModel->getInfo($cityId);
        $cityName = explode('/', $cityInfo[0]['name'])[0];
        $universalTimeModel = D('UniversalTime');
        $universalTimeInfo = $universalTimeModel->getInfo($universalTime);
        $countryId = $universalTimeInfo['country_id'];

        $hotelApplyModel = D('HotelApply');
        // 判断客栈是否已经申请
        $hotelApplyInfo = $hotelApplyModel->getInfoByMobileAndAreaCode($adminLoginInfo['mobile'], $adminLoginInfo['areacode'], array(0,1));
        foreach ($hotelApplyInfo as $key => $hotelApplyItem) {
            if ($hotelApplyItem['hotelname'] == $name) {
                returnJson(403, 423);
            }

            if (!is_null($communityNo) && !is_null($masterentityId) && $communityNo == $hotelApplyItem['communityno'] && $masterentityId == $hotelApplyItem['community_id']) {
                returnJson(403, 423);
            }
        }

        // 添加客栈
        $result = $hotelApplyModel->addInfo($name, $cityName, $adminLoginInfo['mobile'], $adminLoginInfo['name'], 0, '', $universalTime, $adminLoginInfo['areacode'], $countryId, $cityId, $districtId, $communityNo, $masterentityId, null, $currencyId);
        if (!$result) {
            returnJson(500, 508);
        }

        //发送邮件通知
        $email = new \Org\Util\Email();
        foreach (C('SIGNIN_NOTIFICATION_EMAIL') as $emailToSend) {
            $email->applyHotel($emailToSend, $name, $adminLoginInfo['mobile'], $cityName, $adminLoginInfo['name'], '');
        }
        unset($emailToSend);

        return true;
    }

    /**
     * 经销商添加客栈逻辑
     * @modify zhangzhen 2017-1-12  创建
     * @param  string  $name       客栈名
     * @param  integer $cityId     城市id
     * @param  integer $districtId 区id
     * @param  date    $enddate    到期时间
     */
    public function addUserInfo($mobile, $name, $cityId, $districtId, $enddate, $universalTime = '5', $areaCode = '86', $currencyId = null) {
        //检查账号是否属于该经销商
        $adminLoginModel = D('AdminLogin');
        $adminLogin = $adminLoginModel->getInfoByMobile($mobile, $areaCode);
        $dealerAdminModel = D('DealerAdmin');
        $dealerAdmin = $dealerAdminModel->getInfoByUser($adminLogin['id']);
        $dealerId = getDealerId();
        if ($dealerId != $dealerAdmin['dealerlogin_id']) {
            returnJson(403, 211);
        }

        $hotelApplyModel = D('HotelApply');
        // 判断客栈是否已经申请
        $hotelApplyInfo = $hotelApplyModel->getInfoByMobileAndAreaCode($mobile, $areaCode, array(0,1));
        foreach ($hotelApplyInfo as $key => $hotelApplyItem) {
            if ($hotelApplyItem['hotelname'] == $name) {
                returnJson(403, 405);
            }
        }

        $cityModel = D('City');
        $cityInfo = $cityModel->getInfo($cityId);
        $cityName = explode('/', $cityInfo[0]['name'])[0];
        $universalTimeModel = D('UniversalTime');
        $universalTimeInfo = $universalTimeModel->getInfo($universalTime);
        $countryId = $universalTimeInfo['country_id'];

        // 添加客栈
        $hotelApplyModel = D('HotelApply');
        $result = $hotelApplyModel->addInfo($name, $cityName, $adminLogin['mobile'], $adminLogin['name'], $dealerId, '', $universalTime, $adminLogin['areacode'], $countryId, $cityId, $districtId, null, null, $enddate, $currencyId);
        if (!$result) {
            returnJson(500, 508);
        }

        //发送邮件通知
        $email = new \Org\Util\Email();
        foreach (C('SIGNIN_NOTIFICATION_EMAIL') as $emailToSend) {
                $email->dealerApplyHotel($emailToSend, $name, $mobile, $cityName, $adminLogin['name']);
        }
        unset($emailToSend);

        return true;
    }

    /**
     * 经销商添加客栈逻辑
     * @modify zhangzhen 2017-1-12  创建
     * @param  string  $name       客栈名
     * @param  integer $cityId     城市id
     * @param  integer $districtId 区id
     * @param  date    $enddate    到期时间
     */
    public function addUserCharityHotel($mobile, $name, $cityId, $districtId, $enddate, $universalTime = '5', $areaCode = '86', $currencyId = null) {
        //检查账号是否属于该经销商
        $adminLoginModel = D('AdminLogin');
        $adminLogin = $adminLoginModel->getInfoByMobile($mobile, $areaCode);
        $dealerAdminModel = D('DealerAdmin');
        $dealerAdmin = $dealerAdminModel->getInfoByUser($adminLogin['id']);
        $dealerId = getDealerId();
        if ($dealerId != $dealerAdmin['dealerlogin_id']) {
            returnJson(403, 211);
        }

        $userId = $adminLogin['id'];

        $adminHotelModel = D('AdminHotel');
        $hotelEntityModel = D('HotelEntity');
        //检查用户是否已存在此客栈
        $adminHotels = $adminHotelModel->getInfosByAdmin($userId);
        foreach ($adminHotels as $adminHotel) {
            $hotelResult = $hotelEntityModel->getInfo($adminHotel['hotelentity_id']);
            if ($hotelResult['name'] == $name) {
                returnJson(403, 420);
            }
            //检查用户是否已存在义卖客栈
            if ($hotelResult['usage'] == 4) {
                returnJson(403, 424);
            }
        }

        // 添加客栈
        $hotelEntityModel->startTrans();
        $commit = true;
        $addResult = $hotelEntityModel->addInfo($name, $cityId, $districtId, NULL, 4, null, $universalTime);
        if (!$addResult) {
            $commit = false;
        }
        $hotelId = $addResult;

        // 添加客栈默认货币
        if ($commit && !is_null($currencyId)) {
            $currencyHotelModel = D('CurrencyHotel');
            $addResult = $currencyHotelModel->addDefaultCurrency($hotelId, $currencyId, 1);
            if ($addResult == false) {
                $commit = false;
            }
        }

        //经销商所属客户添加客栈设到期时间
        if ($commit) {
            $dealerAdmin = $dealerAdminModel->getInfoByUser($userId);
            $dealerLogin = D('DealerLogin')->getInfo($dealerAdmin['dealerlogin_id']);
            $addResult = $hotelEntityModel->setDate($hotelId, $enddate);
            if (empty($addResult)) {
                $commit = false;
            }
        }       



        // 添加客栈信息记录
        if ($commit) {
            $hotelInfoModel = D('HotelInfo');
            $addResult = $hotelInfoModel->addInfo($hotelId);
            if (empty($addResult)) {
                $commit = false;
            }
        }

        // 添加客栈-人记录
        if ($commit) {
            $addResult = $adminHotelModel->addInfo($hotelId, $userId, HOTEL_ROLE_OWNER);
            if (!$addResult) {
                $commit = false;
            }
        }

        // 添加系统预设数据
        if ($commit) {
            $resourceInfo = $this->getResource();

            $channelData = array();
            foreach ($resourceInfo['channel'] as $channel) {
                array_push($channelData,
                        array(
                    'hotelentity_id' => $hotelId,
                    'name' => $channel,
                    'type' => RESOURCE_NOTDELETABLE,
                    'status' => NOT_DELETE,
                ));
            }
            unset($channel);

            $payData = array();
            foreach ($resourceInfo['pay'] as $pay) {
                array_push($payData,
                        array(
                    'hotelentity_id' => $hotelId,
                    'name' => $pay,
                    'type' => RESOURCE_NOTDELETABLE,
                    'status' => NOT_DELETE,
                ));
            }
            unset($pay);

            if (!empty($channelData)) {
                $hotelChannelModel = D('HotelChannel');
                $addResult = $hotelChannelModel->addInfo($channelData);
                if (!$addResult) {
                    $commit = false;
                }
            }

            if ($commit && !empty($payData)) {
                $hotelPayModel = D('HotelPay');
                $addResult = $hotelPayModel->addInfo($payData);
                if (!$addResult) {
                    $commit = false;
                }
            }
        }
        
        //会员设置为共享时，添加会员信息
        if($commit){
            $vipInitModel = D('VipInit');
            $vipInitInfo = $vipInitModel->getInfoByAdmin($userId);
            if($vipInitInfo['share'] == '1'){
                $adminHotelInfos = $adminHotelModel->getInfosByAdmin($userId);
                $vipInfoModel = D('VipInfo');
                $vipInfos = $vipInfoModel->getInfoByHotel($adminHotelInfos[0]['hotelentity_id']);
                foreach ($vipInfos as $key => $vipInfo) {
                    $addResult = $vipInfoModel->addInfo($vipInfo['name'], $hotelId, $vipInfo['auto'], $vipInitInfo['level'], $vipInfo['levelrule'], $vipInitInfo['discount'], $vipInfo['discountrule']);
                    if (!$addResult) {
                        $commit = false;
                        break;
                    }
                }
            }
        }


        if ($commit) {
            $hotelEntityModel->commit();
            return true;
        } else {
            $hotelEntityModel->rollback();
            returnJson(500, 508, 'error');
        }
    }

    /**
     * 获取客栈列表
     * @modify trainyao 2016-01-04 创建
     * @param  integer   $userId    用户ID
     * @return array 客栈列表
     */
    public function getHotelByUser($userId) {
        return $this->__singleGet('_getHotelByUser', array($userId));
    }
    protected function _getHotelByUser($userId) {
        // 取出管理员-客栈关系
        $adminHotelModel = D('AdminHotel');
        $adminHotelData = $adminHotelModel->getInfoByUser($userId);

        if (empty($adminHotelData)) {
            return array();
        }

        // 取出管理的客栈信息
        $hotelIds = array_column($adminHotelData, 'hotelentity_id');
        $hotelEntityModel = D('HotelEntity');
        $hotelData = $hotelEntityModel->getInfo($hotelIds);
        $hotelInfoModel = D('HotelInfo');
        $hotelInfoData = $hotelInfoModel->getInfoByHotel($hotelIds);

        if (empty($hotelData)) {
            returnJson(500, 512, 'error');
        }

        // 封装数据
        if (count($hotelIds) == 1) {
            $adminHotelData[0]['name'] = $hotelData['name'];
            $adminHotelData[0]['city_id'] = $hotelData['city_id'];
            $adminHotelData[0]['district_id'] = $hotelData['district_id'];
            $adminHotelData[0]['communityno'] = $hotelData['communityno'];
            $adminHotelData[0]['status'] = $hotelData['status'];
            $adminHotelData[0]['usage'] = $hotelData['usage'];
            $adminHotelData[0]['enddate'] = $hotelData['enddate'];
            $adminHotelData[0]['universaltime_id'] = $hotelData['universaltime_id'];
            $adminHotelData[0]['startTime'] = $hotelInfoData['checkintime'] ? $hotelInfoData['checkintime'] : '14:00';
            $adminHotelData[0]['endTime'] = $hotelInfoData['checkouttime'] ? $hotelInfoData['checkouttime'] : '12:00';
            $adminHotelData[0]['splitordertime'] = $hotelInfoData['splitordertime'] ? $hotelInfoData['splitordertime'] : '00:00';
        } else {
            $hotelData = getArrayValueAsIndex($hotelData, 'id');
            $hotelInfoData = getArrayValueAsIndex($hotelInfoData, 'hotelentity_id');

            
            foreach ($adminHotelData as $index => & $data) {
                $hotelId = $data['hotelentity_id'];


                $data['name'] = $hotelData[$hotelId]['name'];
                $data['city_id'] = $hotelData[$hotelId]['city_id'];
                $data['district_id'] = $hotelData[$hotelId]['district_id'];
                $data['communityno'] = $hotelData[$hotelId]['communityno'];
                $data['status'] = $hotelData[$hotelId]['status'];
                $data['usage'] = $hotelData[$hotelId]['usage'];
                $data['enddate'] = $hotelData[$hotelId]['enddate'];
                $data['universaltime_id'] = $hotelData[$hotelId]['universaltime_id'];
                $data['startTime'] = $hotelInfoData[$hotelId]['checkintime'] ? $hotelInfoData[$hotelId]['checkintime'] : '14:00';
                $data['endTime'] = $hotelInfoData[$hotelId]['checkouttime'] ? $hotelInfoData[$hotelId]['checkouttime'] : '12:00';
                $data['splitordertime'] = $hotelInfoData[$hotelId]['splitordertime'] ? $hotelInfoData[$hotelId]['splitordertime'] : '00:00';
            }
        }

        // 取出区信息s
        $districtIds = array_column($adminHotelData, 'district_id');
        $districtIds = array_unique($districtIds);
        $districtModel = D('District');
        $districtInfo = $districtModel->getInfo($districtIds);
        if (count($districtIds) == 1) {
            $districtInfo = array($districtInfo);
        }
        $districtInfo = getArrayValueAsIndex($districtInfo, 'id');
        foreach ($adminHotelData as &$dataItem) {
            switch (LANG_SET) {
                case 'zh_cn':
                    $dataItem['districtName'] = explode('/', $districtInfo[$dataItem['district_id']]['name'])[0];
                    break;
                case 'en_us':
                    $dataItem['districtName'] = explode('/', $districtInfo[$dataItem['district_id']]['name'])[1];
                    break;
                case 'zh_tw':
                    $dataItem['districtName'] = explode('/', $districtInfo[$dataItem['district_id']]['name'])[2];
                    break;
                default:
                    $dataItem['districtName'] = explode('/', $districtInfo[$dataItem['district_id']]['name'])[0];
                    break;
            }
        }
        unset($dataItem);

        return $adminHotelData;
    }

    /**
     * 返回多客栈数据
     * @Modify songanwei 2016-01-08
     * @param type $hotelIds 客栈ID数组 [{id, name, city_id, district_id, communityno, status, enddate}, {}, {},..]
     */
    public function getHotelByHotelId($hotelIds) {
        return $this->__singleGet('_getHotelByHotelId', array($hotelIds));
    }
    protected function _getHotelByHotelId($hotelIds) {
        $hotelEntityModel = D('HotelEntity');
        $hotels = $hotelEntityModel->getInfo($hotelIds);
        $hotelData = array();
        if (count($hotelIds) == 1) {
            $hotelData[0]['id'] = $hotels['id'];
            $hotelData[0]['name'] = $hotels['name'];
            $hotelData[0]['city_id'] = $hotels['city_id'];
            $hotelData[0]['district_id'] = $hotels['district_id'];
            $hotelData[0]['communityno'] = $hotels['communityno'];
            $hotelData[0]['status'] = $hotels['status'];
            $hotelData[0]['usage'] = $hotels['usage'];
            $hotelData[0]['enddate'] = $hotels['enddate'];
        } else {
            $hotelData = $hotels;
        }
        return $hotelData;
    }

    /**
     * 获取客栈分销渠道资源,为缓存加
     * @modify trainyao 2016-01-08 创建
     * @param  integer   $hotelId   客栈id
     * @param  boolean   $getDisabled   是否包括被删除的渠道
     * @return array              客栈分销渠道资源数组
     */
    public function getHotelChannel($hotelId, $getDisabled = true) {
        return $this->__singleGet('_getHotelChannel', array($hotelId, $getDisabled));
    }
    public function _getHotelChannel($hotelId, $getDisabled = true) {
        $hotelChannelModel = D('HotelChannel');
        $data = $hotelChannelModel->getInfoByHotel($hotelId);

        if ($getDisabled !== true) {
            foreach ($data as $index => &$channel) {
                if ($channel['status'] == IS_DELETE) {
                    unset($data[$index]);
                }
                if ($channel['type'] == 1) {
                    switch (LANG_SET) {
                        case 'zh_cn':
                            $channel['name'] = explode('/', $channel['name'])[0];
                            break;
                        case 'en_us':
                            $channel['name'] = explode('/', $channel['name'])[1];
                            break;
                        case 'zh_tw':
                            $channel['name'] = explode('/', $channel['name'])[2];
                            break;
                        default:
                            $channel['name'] = explode('/', $channel['name'])[0];
                            break;
                    }
                } else if (strpos($channel['name'], '/') !== false && strpos($channel['name'], '/') != strrpos($channel['name'], '/')) {
                    switch (LANG_SET) {
                        case 'zh_cn':
                            $channel['name'] = explode('/', $channel['name'])[0];
                            break;
                        case 'en_us':
                            $channel['name'] = explode('/', $channel['name'])[1];
                            break;
                        case 'zh_tw':
                            $channel['name'] = explode('/', $channel['name'])[2];
                            break;
                        default:
                            $channel['name'] = explode('/', $channel['name'])[0];
                            break;
                    }
                }
            }
            $data = array_values($data);
        } else {
            foreach ($data as $index => &$channel) {
                if ($channel['type'] == 1) {
                    switch (LANG_SET) {
                        case 'zh_cn':
                            $channel['name'] = explode('/', $channel['name'])[0];
                            break;
                        case 'en_us':
                            $channel['name'] = explode('/', $channel['name'])[1];
                            break;
                        case 'zh_tw':
                            $channel['name'] = explode('/', $channel['name'])[2];
                            break;
                        default:
                            $channel['name'] = explode('/', $channel['name'])[0];
                            break;
                    }
                } else if (strpos($channel['name'], '/') !== false && strpos($channel['name'], '/') != strrpos($channel['name'], '/')) {
                    switch (LANG_SET) {
                        case 'zh_cn':
                            $channel['name'] = explode('/', $channel['name'])[0];
                            break;
                        case 'en_us':
                            $channel['name'] = explode('/', $channel['name'])[1];
                            break;
                        case 'zh_tw':
                            $channel['name'] = explode('/', $channel['name'])[2];
                            break;
                        default:
                            $channel['name'] = explode('/', $channel['name'])[0];
                            break;
                    }
                }
            }
            $data = array_values($data);
        }
        return $data;
    }

    /**
     * 获取客栈支付方式资源,为缓存加
     * @modify trainyao 2016-01-08 创建
     * @param  integer   $hotelId   客栈id
     * @param  boolean   $getDisabled   是否包括被删除的渠道
     * @param  string   $setLang   设置语言
     * @return array              客栈支付方式资源数组
     */
    public function getHotelPay($hotelId, $getDisabled = true, $setLang = null, $getMemberCard = false) {
        return $this->__singleGet('_getHotelPay', array($hotelId, $getDisabled, $setLang, $getMemberCard));
    }
    protected function _getHotelPay($hotelId, $getDisabled = true, $setLang = null, $getMemberCard = false) {
        $orderPayRecordModel = D('OrderPayRecord');
        $hotelPayModel = D('HotelPay');
        $data = $hotelPayModel->getInfoByHotel($hotelId);

        $setLang = !is_null($setLang) ? $setLang : LANG_SET;
        if ($getDisabled !== true) {
            foreach ($data as $index => &$pay) {
                if ($pay['status'] == IS_DELETE) {
                    unset($data[$index]);
                    continue;
                }
                if (!$getMemberCard) {
                    if (explode('/', $pay['name'])[0] == '会员卡') {
                        unset($data[$index]);
                        continue;
                    }
                }

                if ($pay['type'] == 1) {
                    switch ($setLang) {
                        case 'zh_cn':
                            $pay['name'] = explode('/', $pay['name'])[0];
                            break;
                        case 'en_us':
                            $pay['name'] = explode('/', $pay['name'])[1];
                            break;
                        case 'zh_tw':
                            $pay['name'] = explode('/', $pay['name'])[2];
                            break;
                        default:
                            $pay['name'] = explode('/', $pay['name'])[0];
                            break;
                    }
                } else if (strpos($pay['name'], '/') !== false && strpos($pay['name'], '/') != strrpos($pay['name'], '/')) {
                    switch ($setLang) {
                        case 'zh_cn':
                            $pay['name'] = explode('/', $pay['name'])[0];
                            break;
                        case 'en_us':
                            $pay['name'] = explode('/', $pay['name'])[1];
                            break;
                        case 'zh_tw':
                            $pay['name'] = explode('/', $pay['name'])[2];
                            break;
                        default:
                            $pay['name'] = explode('/', $pay['name'])[0];
                            break;
                    }
                }

                // 是否使用过支付方式
                $recordData = $orderPayRecordModel->getInfosByHotelAndPayId($pay['hotelentity_id'], $pay['id']);
                $pay['isUsePay'] = !empty($recordData) ? 1 : 0;
            }
            $data = array_values($data);
        } else {
            foreach ($data as $index => &$pay) {
                if (!$getMemberCard) {
                    if (explode('/', $pay['name'])[0] == '会员卡') {
                        unset($data[$index]);
                        continue;
                    }
                }

                if ($pay['type'] == 1) {
                    switch ($setLang) {
                        case 'zh_cn':
                            $pay['name'] = explode('/', $pay['name'])[0];
                            break;
                        case 'en_us':
                            $pay['name'] = explode('/', $pay['name'])[1];
                            break;
                        case 'zh_tw':
                            $pay['name'] = explode('/', $pay['name'])[2];
                            break;
                        default:
                            $pay['name'] = explode('/', $pay['name'])[0];
                            break;
                    }
                } else if (strpos($pay['name'], '/') !== false && strpos($pay['name'], '/') != strrpos($pay['name'], '/')) {
                    switch ($setLang) {
                        case 'zh_cn':
                            $pay['name'] = explode('/', $pay['name'])[0];
                            break;
                        case 'en_us':
                            $pay['name'] = explode('/', $pay['name'])[1];
                            break;
                        case 'zh_tw':
                            $pay['name'] = explode('/', $pay['name'])[2];
                            break;
                        default:
                            $pay['name'] = explode('/', $pay['name'])[0];
                            break;
                    }
                }

                // 是否使用过支付方式
                $recordData = $orderPayRecordModel->getInfosByHotelAndPayId($pay['hotelentity_id'], $pay['id']);
                $pay['isUsePay'] = !empty($recordData) ? 1 : 0;
            }
            $data = array_values($data);
        }
        return $data;
    }

    /**
     * 获取系统默认客栈资源
     * @modify trainyao 2016-01-09    创建
     */
    public function getResource() {
        return $this->__singleGet('_getResource');
    }
    protected function _getResource() {
        $return = array();
        $channelModel = D('Channel');
        $return['channel'] = $channelModel->getInfo();
        $return['channel'] = array_column($return['channel'], 'name');

        $payModel = D('Pay');
        $return['pay'] = $payModel->getInfo();
        $return['pay'] = array_column($return['pay'], 'name');

        return $return;
    }

    /**
     * 获取客栈预定相关的信息
     * @modify trainyao 2016-02-01    创建
     * @modify zhangzhen 2017-05-22    新增Type
     * @param  integer   $type     房间类型  钟点房(1)还是间夜房(0) 默认间夜房
     */
    public function getHotelBookingDetail($hotelId, $type=0) {
        return $this->__singleGet('_getHotelBookingDetail', array($hotelId, $type));
    }
    protected function _getHotelBookingDetail($hotelId, $type) {
        switch ($type) {
            case 0:
                $hotelInfoModel = D('HotelInfo');
                $return = $hotelInfoModel->getInfoByHotel($hotelId);
                break;
            case 1:
                $hourRoomInitModel = D('HourRoomInit');
                $return = $hourRoomInitModel->getInfo($hotelId);
                break;
        }
        return $return;
    }

    /**
     * 添加客栈分销渠道逻辑
     * @modify trainyao 2016-01-08   创建
     * @param  integer   $hotelId     客栈id
     * @param  string   $channelName 分销名字
     */
    public function addChannel($hotelId, $channelName) {
        //检查客栈是否已过期
        $this->checkHotelActive($hotelId);
        //检查客栈是否启用
        $this->checkHotelStatus($hotelId);

        $channelInfos = $this->getHotelChannel($hotelId, false);
        if (count($channelInfos) >= MAX_RESOURCE_COUNT) {
            returnJson(403, 406);
        }

        $channelNames = array_column($channelInfos, 'name');
        if (in_array($channelName, $channelNames)) {
            returnJson(403, 404);
        }

        $hotelChannelModel = D('HotelChannel');
        $addResult = $hotelChannelModel->addInfo(array(
            array(
                'hotelentity_id' => $hotelId,
                'name' => $channelName,
                'type' => RESOURCE_DELETABLE,
                'status' => NOT_DELETE,
            )
        ));
        if (!$addResult) {
            returnJson(500, 508);
        }
    }

    /**
     * 删除客栈分销渠道逻辑
     * @modify trainyao 2016-01-08   创建
     * @param  integer   $hotelId     客栈id
     * @param  string   $hotelChannelId 客栈分销渠道记录id
     */
    public function deleteChannel($hotelId, $hotelChannelId) {
        //检查客栈是否已过期
        $this->checkHotelActive($hotelId);
        //检查客栈是否启用
        $this->checkHotelStatus($hotelId);

        $channelInfos = $this->getHotelChannel($hotelId);
        $channelInfos = getArrayValueAsIndex($channelInfos, 'id');
        $hotelChannelIds = array_column($channelInfos, 'id');
        if (!in_array($hotelChannelId, $hotelChannelIds) || $channelInfos[$hotelChannelId]['type'] == RESOURCE_NOTDELETABLE) {
            returnJson(403, 202);
        }

        $hotelChannelModel = D('HotelChannel');
        $deleteResult = $hotelChannelModel->deleteInfo($hotelId, $hotelChannelId);
        if (empty($deleteResult)) {
            returnJson(500, 510);
        }
    }

    /**
     * 添加客栈支付方式逻辑
     * @modify trainyao 2016-01-08   创建
     * @param  integer   $hotelId     客栈id
     * @param  string   $payName 支付方式名字
     */
    public function addPay($hotelId, $payName) {
        //检查客栈是否已过期
        $this->checkHotelActive($hotelId);
        //检查客栈是否启用
        $this->checkHotelStatus($hotelId);

        $payInfos = $this->getHotelPay($hotelId, false);
        if (count($payInfos) >= MAX_RESOURCE_COUNT) {
            returnJson(403, 406);
        }

        $payNames = array_column($payInfos, 'name');
        if (in_array($payName, $payNames)) {
            returnJson(403, 404);
        }

        $hotelPayModel = D('HotelPay');
        $addResult = $hotelPayModel->addInfo(array(
            array(
                'hotelentity_id' => $hotelId,
                'name' => $payName,
                'type' => RESOURCE_DELETABLE,
                'status' => NOT_DELETE,
            )
        ));
        if (!$addResult) {
            returnJson(500, 508);
        }
    }

    /**
     * 删除客栈支付方式逻辑
     * @modify trainyao 2016-01-08   创建
     * @param  integer   $hotelId     客栈id
     * @param  string   $hotelPayId 客栈支付方式记录id
     */
    public function deletePay($hotelId, $hotelPayId) {
        //检查客栈是否已过期
        $this->checkHotelActive($hotelId);
        //检查客栈是否启用
        $this->checkHotelStatus($hotelId);

        $payInfos = $this->getHotelPay($hotelId);
        $payInfos = getArrayValueAsIndex($payInfos, 'id');
        $hotelPayIds = array_column($payInfos, 'id');
        if (!in_array($hotelPayId, $hotelPayIds) || $payInfos[$hotelPayId]['type'] == RESOURCE_NOTDELETABLE) {
            returnJson(403, 202);
        }

        $hotelPayModel = D('HotelPay');
        $deleteResult = $hotelPayModel->deleteInfo($hotelId, $hotelPayId);
        if (empty($deleteResult)) {
            returnJson(500, 510);
        }
    }

    /**
     * 保存(多个)客栈禁用启用状态
     * 方法会抛异常
     * @modify trainyao 2016-07-28      创建
     * @param  mixin   $hotelId        客栈ID(s)
     * @param  integer   $status         客栈禁用启用状态 0=启用 1=禁用
     * @return boolean                  执行结果
     */
    public function saveHotelStatus($hotelId, $status) {
        $hotelEntityModel = D('HotelEntity');
        if (!$this->getMultiTransMode()) {
            $hotelEntityModel->startTrans();
        }
        $commit = true;
        
        // 执行修改
        $result = $hotelEntityModel->toggleUse($hotelId, $status);
        if (empty($result)) {
            $commit = false;
        }
        //有开通微预定的要关停微预定
        $hotelDetailModel =  D('HotelDetail');
        foreach ($hotelId as $hotel) {
            $hotelDetail = $hotelDetailModel->where(array('hotelentity_id' => $hotel))->find();
            if($hotelDetail){
                $result = $hotelDetailModel->toggleUse($hotel, $status);
                if (empty($result)) {
                    $commit = false;
                }
            }

        }
        // 修改接口服务
        if ($commit) {
            $interfaceServerLogic = A('Common/InterfaceServer', 'Logic');
            $saveResult = $interfaceServerLogic->saveInterfaceServer($hotelId, null, null, null, $status);
            if ($saveResult == false) {
                $commit = false;
            }
        }
        
        if ($commit) {
            if (!$this->getMultiTransMode()) {
                $hotelEntityModel->commit();
            }

            return true;
        } else {
            if (!$this->getMultiTransMode()) {
                $hotelEntityModel->rollback();
            }
            throw new \Exception('500,506', 506);
            return false;
        }
    }

    public function dealerSetHotelActive($hotel, $status){
        $hotelEntityModel = D('HotelEntity');
        $hotelEntity = $hotelEntityModel->getInfo($hotel);
        if ($status == 0) {
            $updatetime = $hotelEntity['enddate'];
            $enddate = date("Y-m-d",strtotime("-1 day"));
            $result = $hotelEntityModel->setActive($hotel, $enddate, $updatetime);
            return $enddate;
        } elseif($status == 1) {
            $enddate = $hotelEntity['updatetime'];
            $result = $hotelEntityModel->setActive($hotel, $enddate);
            return mb_substr($enddate,0,10);
        } else {
            returnJson(403, 212);
        }
    }

    /**
     * 获取区号时区数据
     * @modify wenhui 2017-06-16
     * @return array $data 时区数据
     */
    public function universalTimeList($lang = null) {
        $universalTimeModel = D('UniversalTime');
        $universalTimeInfo =  $universalTimeModel->getAll();
        if(empty($universalTimeInfo)){
            return array(
                array(
                    'fullName' => '中国',
                    'firstName' => 'C',
                    'areaCode' => '86',
                    'universalTimeId' => '5',
                    'universalTimeUtc' => 'UTC/GMT+8',
                    'universalTimeName' => '中国/China',
                    'universalTimeTimezone' => 'GMT+8',
                    'universalTimeEtc' => 'Etc/GMT-8',
                ),
            );
        }
        $result = [];
        foreach ($universalTimeInfo as $ac){
            $result['zh_cn'][] = array(
                'fullName' => $ac['cnfullname'],
                'firstName' => $ac['cnfirstname'],
                'areaCode' => $ac['areacode'],
                'universalTimeId' => $ac['id'],
                'universalTimeUtc' => $ac['utc'],
                'universalTimeName' => $ac['name'],
                'universalTimeTimezone' => $ac['timezone'],
                'countryId' => $ac['country_id'],
                'universalTimeEtc' => $ac['etc'],
            );
            $result['zh_tw'][] = array(
                'fullName' => $ac['twfullname'],
                'firstName' => $ac['twfirstname'],
                'areaCode' => $ac['areacode'],
                'universalTimeId' => $ac['id'],
                'universalTimeUtc' => $ac['utc'],
                'universalTimeName' => $ac['name'],
                'universalTimeTimezone' => $ac['timezone'],
                'countryId' => $ac['country_id'],
                'universalTimeEtc' => $ac['etc'],
            );
            $result['en_us'][] = array(
                'fullName' => $ac['enfullname'],
                'firstName' => $ac['enfirstname'],
                'areaCode' => $ac['areacode'],
                'universalTimeId' => $ac['id'],
                'universalTimeUtc' => $ac['utc'],
                'universalTimeName' => $ac['name'],
                'universalTimeTimezone' => $ac['timezone'],
                'countryId' => $ac['country_id'],
                'universalTimeEtc' => $ac['etc'],
            );
        }
        $lang = isset($lang)? $lang : LANG_SET;
        return $result[$lang];
        
    }

    /**
     * 保存小黑板内容
     * @modify wenhui 2017-08-28   创建
     * @param  integer   $hotelId     客栈id
     * @param  string   $blackBoardContent 内容
     */
    public function saveHotelBlackboard($hotelId, $blackBoardContent) {
        $hotelBlackBoardModel = D('HotelBlackBoard');

        $hotelBlackBoardInfo = $hotelBlackBoardModel->getBlackBoardContent($hotelId);
        if (empty($hotelBlackBoardInfo)) {
            $saveResult = $hotelBlackBoardModel->addBlackBoardContent($hotelId, $blackBoardContent);
        } else {
            $saveResult = $hotelBlackBoardModel->saveBlackBoardContent($hotelBlackBoardInfo['id'], $blackBoardContent);
        }

        if ($saveResult == false) {
            returnJson(500, 508);
        }

        return true;
    }

    /**
     * 保存小黑板内容
     * @modify wenhui 2017-08-28   创建
     * @param  integer   $hotelId     客栈id
     * @return  data    内容
     */
    public function getHotelBlackboard($hotelId) {
        $hotelBlackBoardModel = D('HotelBlackBoard');

        $hotelBlackBoardInfo = $hotelBlackBoardModel->getBlackBoardContent($hotelId);
        // 处理数据
        if (!empty($hotelBlackBoardInfo)) {
            return array(
                'blackBoardId' => $hotelBlackBoardInfo['id'],
                'hotel' => $hotelBlackBoardInfo['hotelentity_id'],
                'blackBoardContent' => $hotelBlackBoardInfo['content'],
            );
        } else {
            return array(
                'blackBoardId' => '',
                'hotel' => '',
                'blackBoardContent' => '',
            );
        }
    }

    /**
     * 获取闹钟提醒列表
     * @modify wenhui 2017-08-28   创建
     * @param  integer   $hotelId     客栈id
     * @param  integer   $currentPage     页码
     * @param  integer   $pageSize     页数
     * @param  string   $keys     搜索关键字
     * @return  data    内容
     */
    public function getRemindList($hotelId, $currentPage, $pageSize, $keys, $reminded = null, $newstype = null) {
        $hotelAlarmClockModel = D('HotelAlarmClock');
        $hotelEntityModel = D('HotelEntity');
        $adminLoginModel = D('AdminLogin');

        $remindData = $hotelAlarmClockModel->getRemindListByHotel($hotelId, $reminded, $newstype);
        if (empty($remindData)) {
            return array();
        }

        // 处理数据
        $remindLists = array();
        foreach ($remindData as $key => $remindItems) {
            // keys 筛选
            if (!is_null($keys)) {
                if (strpos($remindItems['content'], $keys) === false) {
                    continue;
                }
            }

            $hotelInfo = $hotelEntityModel->getInfo($remindItems['hotelentity_id']);
            $adminLoginInfo = $adminLoginModel->getInfo($remindItems['operator']);
            $hotelname = $hotelInfo['name'];
            $remindItem = array(
                'alarmClockId' => $remindItems['id'],
                'hotel' => $remindItems['hotelentity_id'],
                'hotelName' => $hotelname,
                'content' => $remindItems['content'],
                'remindDate' => date('Y-m-d H:i', strtotime($remindItems['remindtime'])),
                'remind' => $remindItems['reminded'],
                'isRead' => $remindItems['newstype'],
                'recentOperator' => $adminLoginInfo['name'],
                'truereMindDate' => $remindItems['trueremindtime'],
                'remindstamp' => strtotime($remindItems['trueremindtime']),
            );

            array_push($remindLists, $remindItem);
        }
        unset($remindItems);

        /**
         *  排序
         *  排序方式 推荐客栈按点击量  有城市搜索 按最近距离
         *  SORT_ASC - 默认，按升序排列。(A-Z)
         *  SORT_DESC - 按降序排列。(Z-A)
         *  随后可以指定排序的类型：
         *  SORT_REGULAR - 默认。将每一项按常规顺序排列。
         *  SORT_NUMERIC - 将每一项按数字顺序排列。
         *  SORT_STRING - 将每一项按字母顺序排列
         */
        $remindLists = my_sort($remindLists, 'remindstamp', SORT_DESC, SORT_NUMERIC);

        // 分页
        $hotelRemindList = generatePageInfo($remindLists, $currentPage, $pageSize);
        $remindList['remindList'] = $hotelRemindList['hotelInfo'];
        $remindList['page'] =  [
            'current' => $hotelRemindList['page']['current'],
            'size' => $hotelRemindList['page']['size'],
            'total' => $hotelRemindList['page']['total'],
            'pageTotal' => $hotelRemindList['page']['pageTotal'],
        ];

        return $remindList;
    }

    /**
     * 获取闹钟提醒列表
     * @modify wenhui 2017-08-28   创建
     * @param  integer   $hotelId     客栈id
     * @param  integer   $remindDate     提醒时间
     * @param  integer   $content     提醒内容
     * @param  integer   $alarmClockId     tb_hotel_alarm_clock.id
     * @param  integer   $isRead     是否已读
     * @return  bool
     */
    public function saveRemind($hotelId, $remindDate, $content, $alarmClockId, $dropRemind, $isRead) {
        $hotelAlarmClockModel = D('HotelAlarmClock');

        if (is_null($alarmClockId)) {
            // 添加数据
            $alarmClockId = $saveResult = $hotelAlarmClockModel->addRemind($hotelId, $remindDate, $content);
            if (!$saveResult) {
                returnJson(500, 508);
            }
        } else {
            // 保存数据
            $saveResult = $hotelAlarmClockModel->saveRemind($hotelId, $remindDate, $content, $alarmClockId, $dropRemind, $isRead);
            if (!$saveResult) {
                returnJson(500, 509);
            }
        }

        // 保存redis数据
        $redis = new \Org\Util\RedisHelper(C('REDIS_SERVERIP'), C('REDIS_SERVERPORT'), C('REDIS_ORDER_REMIND_DB'));
        $redis->db(C('REDIS_ORDER_REMIND_DB'));
        if (is_null($dropRemind) && is_null($isRead)) {
            // 构造推送消息
            $hotelData = D('HotelEntity')->getInfo($hotelId);
            $alert = [
                'zh_cn' => '[前台提醒]' . $hotelData['name'] . ': ' . $remindDate . ',' . $content,
                'en_us' => '[Reminder]' . $hotelData['name'] . ': ' . $remindDate . ',' . $content,
            ];
            if ($hotelData['universaltime_id'] == 5) {
                $alertNews = $alert['zh_cn'];
            } else {
                $alertNews = $alert['en_us'];
            }

            $data = array(
                'remindTime' =>  strtotime($remindDate),
                'content' =>  $content,
                'hotel' =>  $hotelId,
                'alarmClockId' =>  $alarmClockId,
                'alertNews' =>  $alertNews,
            );
            $key = $redis->table('remind')->hMSet('_' . $alarmClockId, $data);
            $key = $redis->table('appRemind')->hMSet('_' . $alarmClockId, $data);
        } else if (!is_null($dropRemind) && $dropRemind ==1) {
            // 使消息失效
            $redis->table('remind')->myexpiry('_' . $alarmClockId, 0);
            $redis->table('appRemind')->myexpiry('_' . $alarmClockId, 0);
        }

        return true;
    }

    /**
     * 获取闹钟提醒列表
     * @modify wenhui 2017-08-28   创建
     * @param  integer   $hotelId     客栈id
     * @param  integer   $remindDate     提醒时间
     * @param  integer   $content     提醒内容
     * @param  integer   $alarmClockId     tb_hotel_alarm_clock.id
     * @param  integer   $isRead     是否已读
     * @return  bool
     */
    public function getRemind($alarmClockId) {
        $hotelAlarmClockModel = D('HotelAlarmClock');

        // 获取数据
        $dataResult = $hotelAlarmClockModel->getRemindById($alarmClockId);
        if (empty($dataResult)) {
            returnJson(500, 504);
        }

        return $dataResult;
    }

    /**
     * 保存客栈办理入住状态
     * 方法会抛异常
     * @modify wenhui 2017-10-10 创建
     * @param  integer   $hotelId   客栈ID
     * @param  integer   $type      保存客栈办理入住状态
     * @return boolean              保存结果
     */
    public function saveCheckinType($hotelId, $type) {
        // 保存支付类型
        $hotelCheckinUsableModel = D('HotelCheckinUsable');
        $result = $hotelCheckinUsableModel->getInfo($hotelId);
        $commit = true;
        if (empty($result)) {
            $addResult = $hotelCheckinUsableModel->addInfo($hotelId, $type);
            if (empty($addResult)) {
                $commit = false;
            }
        } else {
            $saveResult = $hotelCheckinUsableModel->saveInfo($hotelId, $type);
            if (empty($saveResult)) {
                $commit = false;
            }
        }

        if (!$commit) {
            throw new \Exception('500,506', 506);
            return false;
        }

        return true;
    }


    /**
     * 检查客栈启用、禁用状态
     * @modify songanwei 2016-02-01
     * @param integer $hotelId 客栈ID
     */
    public function checkHotelStatus($hotelId) {
        $hotel = $this->getHotelByHotelId($hotelId);
        if ($hotel[0]['status'] == IS_DELETE) {
            if (IS_POST) {
                returnJson(403, 401);
            }
            return false;
        }
        return true;
    }

    /**
     * 检查客栈使用状态
     * @modify wenhui 2017-09-12
     * @param integer $hotelId 客栈ID
     */
    public function checkFreeHotel($hotelId) {
        $hotel = $this->getHotelByHotelId($hotelId);
        if ($hotel[0]['usage'] == 4) {
            return true;
        }
        return false;
    }

     /**
     * 检查客栈使用状态
     * @modify wenhui 2017-09-12
     * @param integer $hotelId 客栈ID
     */
    public function checkHotelUsage($hotelId, $usage) {
        $hotel = $this->getHotelByHotelId($hotelId);
        if (in_array($hotel[0]['usage'], $usage)) {
            return true;
        }
        return false;
    }
	
	/**
     * 检查账户是否在有效期内
     * @modify zhangzhen 2016-12-29
     * @modify zhangzhen 2017-1-5 添加经销商
     * @param integer $adminId 管理员id
     */
	public function checkUserActive($adminId = null){
		$adminId = $adminId ? $adminId : getUserId();
		$AdminLoginModel = D('AdminLogin');
		$result = $AdminLoginModel->getInfo($adminId);
		/*if( ($result['status'] == 1 && $result['endtime']<date('Y-m-d')) || ($result['status'] == 2 && $result['endtime']<date('Y-m-d')) || ($result['status'] == 4 && $result['endtime']<date('Y-m-d'))){
            //经销商的掌柜不设置过期标志
            if($result['status'] != 4){
                $AdminLoginModel->setStatus($adminId, 0);
            }
			$AdminHotelModel = D('AdminHotel');
			$AdminHotelDetail = $AdminHotelModel->getInfosByAdmin($adminId);
			foreach($AdminHotelDetail as $oneDetail){
				$hotel[] = $oneDetail['hotelentity_id'];
			}
			$hotelEntityModel = D('HotelEntity');
			$hotelEntityModel->setDate($hotel, $result['endtime']);
			return false;
		}elseif ($result['status'] == 0 || $result['status'] == 2){
			return false;
		}else{
            return $result['status'];
        }*/

        if(($result['status'] == 4 && $result['endtime']<date('Y-m-d'))){
            $AdminHotelModel = D('AdminHotel');
            $AdminHotelDetail = $AdminHotelModel->getInfosByAdmin($adminId);
            foreach($AdminHotelDetail as $oneDetail){
                $hotel[] = $oneDetail['hotelentity_id'];
            }
            $hotelEntityModel = D('HotelEntity');
            $hotelEntityModel->setDate($hotel, $result['endtime']);
        }

        return $result['status'];
	}
	
    /**
     * 检查客栈是否在有效期内
     * @modify songanwei 2016-03-21
     * @param integer $hotelId 客栈ID
     */
    public function checkHotelActive($hotelId, $ajax = false) {
		$this->checkUserActive();
        $hotel = $this->getHotelByHotelId($hotelId);
        //检查客栈是否已过期
        if ($hotel[0]['enddate'] != '0000-00-00') {
            $currentDate = date('Y-m-d');
            if ($hotel[0]['enddate'] < $currentDate) {
                if ($ajax || IS_POST) {
                    returnJson(403, 408);
                }
                return false;
            }
        }
        return true;
    }
    public function checkHotelAppEnable($hotelId)
    {
        $hotelAppModel = D('HotelApp');
        $appInfo = $hotelAppModel->getInfo($hotelId);
        if(empty($appInfo)){
            return false;
        }
        if($appInfo['status']!=1){
            return false;
        }
        if(time()>strtotime($appInfo['enddate'])){
            return false;
        }
        return true;
    }

     /**
     * 检查手机号是否存在
     * @param  string $mobile 手机号
     * @return array         查询结果
     */
    public function checkMobile($mobile, $areaCode = '86') {
        $hotelApplyModel = D('HotelApply');
        $hotelApply = $hotelApplyModel->getInfoByMobile($mobile, $areaCode);
        if ($hotelApply) {
            return $hotelApply; 
        }
        $adminLoginModel = D('AdminLogin');
        $adminLogin = $adminLoginModel->getInfoByMobile($mobile, $areaCode);
        $adminHotelModel = D('AdminHotel');
        $result = $adminHotelModel->getInfosByAdmin($adminLogin['id']);
        return $result;
    }
    
    /**
     * 获取省份
     * @modify wenhui 2017-09-15
     */
    public function getProvinceList($universalTimeId) {
        //获取城市
        $universalTimeModel = D('UniversalTime');
        $provinceModel = D('Province');
        $universalTimeInfo = $universalTimeModel->getInfo($universalTimeId);
        $provinceInfo = $provinceModel->getInfoByCountry($universalTimeInfo['country_id']);
        
        $data = array();
        foreach ($provinceInfo as $provinceItem) {
            switch (LANG_SET) {
                case 'zh_cn' :
                    $provincName = explode('/',$provinceItem['name'])[0];
                    break;
                case 'en_us' :
                    $provincName = explode('/',$provinceItem['name'])[1];
                    break;
                case 'zh_tw' :
                    $provincName = explode('/',$provinceItem['name'])[2];
                    break;
                default:
                    $provincName = explode('/',$provinceItem['name'])[0];
                    break;
            }
            $provinceArray = array(
                'provinceId' => $provinceItem['id'],
                'provincName' => $provincName,
            );
            array_push($data, $provinceArray);
        }
        unset($provinceItem);
        
        return $data;
    }
    
    /**
     * 获取城市
     * @modify wenhui 2017-09-15
     */
    public function getCityList($provinceId) {
        //获取城市
        $cityModel = D('City');
        $cityInfo = $cityModel->getInfoByProvince($provinceId);

        $data = array();
        foreach ($cityInfo as $cityItem) {
            switch (LANG_SET) {
                case 'zh_cn' :
                    $cityName = explode('/',$cityItem['name'])[0];
                    break;
                case 'en_us' :
                    $cityName = explode('/',$cityItem['name'])[1];
                    break;
                case 'zh_tw' :
                    $cityName = explode('/',$cityItem['name'])[2];
                    break;
                default:
                    $cityName = explode('/',$cityItem['name'])[0];
                    break;
            }
            $cityArray = array(
                'cityId' => $cityItem['id'],
                'cityName' => $cityName,
            );
            array_push($data, $cityArray);
        }
        unset($cityItem);
        
        return $data;
    }

    /**
     * 获取区数据
     * @modify trainyao 2016-01-04    创建
     * @modify trainyao 2017-06-08    多语言
     */
    public function getDistrictList($cityId) {
        $districtModel = D('District');
        $districtData = $districtModel->getInfoByCity($cityId);
        $data = array();
        // 选择语言
        foreach ($districtData as $key => $districtDataItem) {
            switch (LANG_SET) {
                case 'zh_cn':
                    $districtName = explode('/', $districtDataItem['name'])[0];
                    break;
                case 'en_us':
                    $districtName = explode('/', $districtDataItem['name'])[1];
                    break;
                case 'zh_tw':
                    $districtName = explode('/', $districtDataItem['name'])[2];
                    break;
                default:
                    $districtName = explode('/', $districtDataItem['name'])[0];
                    break;
            }
            $districtArray = array(
                'districtId' => $districtDataItem['id'],
                'districtName' => $districtName,
            );
            array_push($data, $districtArray);
        }
        unset($districtDataItem);

        return $data;
    }

    /**
     * 添加记一笔项目
     * @modify wenhui 2017-12-19 创建
     * @param  integer   $hotelId     客栈id
     * @param  string   $NoteName 项目名称
     * @param  integer   $type 项目类型  1=收入项目 2=支出项目
     */
    public function addNote($hotelId, $noteName, $type) {
        //检查客栈是否已过期
        $this->checkHotelActive($hotelId);
        //检查客栈是否启用
        $this->checkHotelStatus($hotelId);

        $noteInfos = $this->getHotelNote($hotelId, $type);
        if (count($noteInfos) >= MAX_RESOURCE_COUNT) {
            returnJson(403, 406);
        }

        $noteNames = array_column($noteInfos, 'name');
        if (in_array($noteName, $noteNames)) {
            returnJson(403, 430);
        }

        $hotelNoteModel = D('HotelNote');
        $noteId = $addResult = $hotelNoteModel->addNote(
            array(
                'hotelentity_id' => $hotelId,
                'name' => $noteName,
                'type' => $type,
            )
        );
        if (!$addResult) {
            returnJson(500, 508);
        }

        return $noteId;
    }

    /**
     * 修改记一笔项目
     * @modify wenhui 2017-12-19 创建
     * @param  integer   $hotelId     客栈id
     * @param  string   $noteId 记一笔id
     * @param  string   $name 名称
     */
    public function editNote($hotelId, $noteId, $name) {
        //检查客栈是否已过期
        $this->checkHotelActive($hotelId);
        //检查客栈是否启用
        $this->checkHotelStatus($hotelId);

        $noteInfos = $this->getHotelNote($hotelId);
        $noteInfos = getArrayValueAsIndex($noteInfos, 'id');
        $hotelNoteIds = array_column($noteInfos, 'id');
        if (!in_array($noteId, $hotelNoteIds)) {
            returnJson(403, 202);
        }

        $hotelNoteModel = D('HotelNote');
        $saveResult = $hotelNoteModel->saveInfo($hotelId, $noteId, $name);
        if ($saveResult === false) {
            returnJson(500, 506);
        }

        return true;
    }

    /**
     * 删除记一笔项目
     * @modify wenhui 2017-12-19 创建
     * @param  integer   $hotelId     客栈id
     * @param  string   $hotelNoteId 客栈记一笔id
     */
    public function deleteNote($hotelId, $hotelNoteId) {
        //检查客栈是否已过期
        $this->checkHotelActive($hotelId);
        //检查客栈是否启用
        $this->checkHotelStatus($hotelId);

        $noteInfos = $this->getHotelNote($hotelId);
        $noteInfos = getArrayValueAsIndex($noteInfos, 'id');
        $hotelNoteIds = array_column($noteInfos, 'id');
        if (!in_array($hotelNoteId, $hotelNoteIds)) {
            returnJson(403, 202);
        }

        $hotelNoteModel = D('HotelNote');
        $deleteResult = $hotelNoteModel->deleteInfo($hotelId, $hotelNoteId);
        if (empty($deleteResult)) {
            returnJson(500, 510);
        }
    }

     /**
     * 获取客栈记一笔项目,为缓存加
     * @modify wenhui 2017-12-19 创建
     * @param  integer   $hotelId   客栈id
     * @param  boolean   $getDisabled   是否包括被删除的项目
     * @param  boolean   $type   类型
     * @param  boolean   $isDiffType   是否分类型
     * @return array              客栈记一笔资源数组
     */
    public function getHotelNote($hotelId, $getDisabled = false, $type = null, $isDiffType = false) {
        return $this->__singleGet('_getHotelNote', array($hotelId, $getDisabled, $type, $isDiffType));
    }
    protected function _getHotelNote($hotelId, $getDisabled = false, $type = null, $isDiffType = false) {
        $hotelNoteModel = D('HotelNote');
        $data = $hotelNoteModel->getInfoByHotel($hotelId, $type);

        $noteModel = D('Note');
        // 收入是否为空
        $incomeData = $hotelNoteModel->getInfoByHotelAndType($hotelId, 1);
        if (empty($incomeData)) {
            $notes = $noteModel->getInfoByType(1);
            foreach ($notes as $note) {
                $hotelNoteData[] = array(
                    'hotelentity_id' => $hotelId,
                    'name' => $note['name'],
                    'type' => $note['type'],
                );
            }
            unset($note);
        }

        // 支出是否为空
        $outData = $hotelNoteModel->getInfoByHotelAndType($hotelId, 2);
        if (empty($outData)) {
            $notes = $noteModel->getInfoByType(2);
            foreach ($notes as $note) {
                $hotelNoteData[] = array(
                    'hotelentity_id' => $hotelId,
                    'name' => $note['name'],
                    'type' => $note['type'],
                );
            }
            unset($note);
        }

        if (!empty($hotelNoteData)) {
            $result = $hotelNoteModel->addAll($hotelNoteData);
            // 重新获取数据
            $data = $hotelNoteModel->getInfoByHotel($hotelId, $type);
        }


        $langSet = LANG_SET;
        foreach ($data as $key => &$item) {
            if (strpos($item['name'], '/') !== false) {
                $name = explode('/', $item['name']);
                if ($langSet == 'zh_cn') {
                    $item['name'] = $name[0];
                } else if ($langSet == 'en_us') {
                    $item['name'] = $name[1];
                } else if ($langSet == 'zh_tw') {
                    $item['name'] = $name[2];
                } else {
                    $item['name'] = $name[0];
                }
            }
        }
        unset($item);

        if ($getDisabled !== true) {
            foreach ($data as $index => &$note) {
                if ($note['isdelete'] == IS_DELETE) {
                    unset($data[$index]);
                }
            }
            $data = array_values($data);
        }

        // 是否分类型
        if ($isDiffType) {
            $returnData['income'] = [];
            $returnData['outcome'] = [];

            foreach ($data as $key => $item) {
                if ($item['type'] == NOTE_INCOME) {
                    array_push($returnData['income'], $item);
                } else {
                    array_push($returnData['outcome'], $item);
                }
            }
            unset($item);

            return $returnData;
        }

        return $data;
    }

    /**
     * 添加他消费项目
     * @modify wenhui 2017-12-19 创建
     * @param  integer   $hotelId     客栈id
     * @param  string   $name 项目名称
     */
    public function addOtherCost($hotelId, $name) {
        //检查客栈是否已过期
        $this->checkHotelActive($hotelId);
        //检查客栈是否启用
        $this->checkHotelStatus($hotelId);

        $costInfos = $this->getHotelOtherCost($hotelId);
        if (count($costInfos) >= MAX_RESOURCE_COUNT) {
            returnJson(403, 406);
        }

        $costNames = array_column($costInfos, 'name');
        if (in_array($name, $costNames)) {
            returnJson(403, 430);
        }

        $hotelOtherCostModel = D('HotelOtherCost');
        $addResult = $hotelOtherCostModel->addOtherCost(
            array(
                'hotelentity_id' => $hotelId,
                'name' => $name,
            )
        );
        if (!$addResult) {
            returnJson(500, 508);
        }
    }

    /**
     * 修改他消费项目
     * @modify wenhui 2017-12-19 创建
     * @param  integer   $hotelId     客栈id
     * @param  string   $costId 客栈记一笔id
     * @param  string   $name 名称
     */
    public function editOtherCost($hotelId, $costId, $name) {
        //检查客栈是否已过期
        $this->checkHotelActive($hotelId);
        //检查客栈是否启用
        $this->checkHotelStatus($hotelId);

        $costInfos = $this->getHotelOtherCost($hotelId);
        $costInfos = getArrayValueAsIndex($costInfos, 'id');
        $hotelCostIds = array_column($costInfos, 'id');
        if (!in_array($costId, $hotelCostIds)) {
            returnJson(403, 202);
        }

        $hotelOtherCostModel = D('HotelOtherCost');
        $saveResult = $hotelOtherCostModel->saveInfo($hotelId, $costId, $name);
        if ($saveResult === false) {
            returnJson(500, 508);
        }
        return true;
    }

    /**
     * 删除他消费项目
     * @modify wenhui 2017-12-19 创建
     * @param  integer   $hotelId     客栈id
     * @param  string   $costId 客栈记一笔id
     */
    public function deleteOtherCost($hotelId, $costId) {
        //检查客栈是否已过期
        $this->checkHotelActive($hotelId);
        //检查客栈是否启用
        $this->checkHotelStatus($hotelId);

        $costInfos = $this->getHotelOtherCost($hotelId);
        $costInfos = getArrayValueAsIndex($costInfos, 'id');
        $hotelCostIds = array_column($costInfos, 'id');
        if (!in_array($costId, $hotelCostIds)) {
            returnJson(403, 202);
        }

        $hotelOtherCostModel = D('HotelOtherCost');
        $deleteResult = $hotelOtherCostModel->deleteOtherCost($hotelId, $costId);
        if (empty($deleteResult)) {
            returnJson(500, 510);
        }
    }

     /**
     * 获取他消费项目,为缓存加
     * @modify wenhui 2017-12-19 创建
     * @param  integer   $hotelId   客栈id
     * @param  boolean   $getDisabled   是否包括被删除的项目
     * @return array              客栈支付方式资源数组
     */
    public function getHotelOtherCost($hotelId, $getDisabled = false) {
        return $this->__singleGet('_getHotelOtherCost', array($hotelId, $getDisabled));
    }
    protected function _getHotelOtherCost($hotelId, $getDisabled = false) {
        $hotelOtherCostModel = D('HotelOtherCost');
        $data = $hotelOtherCostModel->getInfoByHotel($hotelId);

        if ($getDisabled !== true) {
            foreach ($data as $index => &$cost) {
                if ($cost['isdelete'] == IS_DELETE) {
                    unset($data[$index]);
                }
            }
            $data = array_values($data);
        }

        return $data;
    }

    /**
     * 添加记一笔记录
     * @modify wenhui 2017-12-19 创建
     * @param  integer   $hotelId     客栈id
     * @param  integer   $noteCostId     记一笔记录id
     */
    public function getNoteCost($hotelId, $noteCostId) {
        //检查客栈是否已过期
        $this->checkHotelActive($hotelId);
        //检查客栈是否启用
        $this->checkHotelStatus($hotelId);

        $hotelNoteCostModel = D('HotelNoteCost');
        $noteCostInfo = $hotelNoteCostModel->getNoteCost($hotelId, $noteCostId);
        if (empty($noteCostInfo)) {
            return array();
        }

        // 获取支付方式信息用作补充
        $hotelLogic = A('Common/Hotel', 'Logic');
        $payResource = $hotelLogic->getHotelPay($hotelId, true, null, true);
        $payResource = getArrayValueAsIndex($payResource, 'id');

        // 获取记一笔项目信息用作补充
        $noteResource = $hotelLogic->getHotelNote($hotelId, true);
        $noteResource = getArrayValueAsIndex($noteResource, 'id');

        // 获取客栈所有管理者信息用作补充（包括删除的管理员）
        $adminHotelModel = D('AdminHotel');
        $adminLoginModel = D('AdminLogin');
        $userInfos = $adminHotelModel->getUserInfoByHotel($hotelId);
        $userIds = array_column($userInfos, 'adminlogin_id');
        $hotelInfos = $adminLoginModel->getInfoByAdminId($userIds);
        $hotelInfos = getArrayValueAsIndex($hotelInfos, 'id');

        // 补充信息
        $data = array();
        foreach ($noteCostInfo as $key => &$cost) {
            array_push($data, array(
                'noteCostId' => $cost['id'],
                'hotelId' => $cost['hotelentity_id'],
                'noteId' => $cost['hotelnote_id'],
                'payId' => $cost['hotelpay_id'],
                'type' => $cost['type'],
                'noteDate' => $cost['date'],
                'noteName' => $noteResource[$cost['hotelnote_id']]['name'],
                'notePrice' => $cost['price'],
                'notePay' => $payResource[$cost['hotelpay_id']]['name'],
                'noteRemark' => $cost['remark'],
                'noteOperator' => $hotelInfos[$cost['operator']]['name'],
            ));
        }
        unset($cost);

        return $data;
    }

    /**
     * 添加记一笔记录
     * @modify wenhui 2017-12-19 创建
     * @param  integer   $hotelId     客栈id
     * @param  integer   $noteId     记一笔项目id
     * @param  integer   $payId     支付方式id
     * @param  integer   $type 记一笔记录类型  1=收入 2=支出
     * @param  decimal   $price 金额
     * @param  string   $noteDate 记一笔记录日期
     * @param  string   $remark 详情
     */
    public function addNoteCost($hotelId, $noteId, $payId, $type, $price, $noteDate, $remark) {
        //检查客栈是否已过期
        $this->checkHotelActive($hotelId);
        //检查客栈是否启用
        $this->checkHotelStatus($hotelId);

        $hotelNoteCostModel = D('HotelNoteCost');
        $addResult = $hotelNoteCostModel->addNoteCost(
            array(
                'hotelentity_id' => $hotelId,
                'hotelnote_id' => $noteId,
                'hotelpay_id' => $payId,
                'type' => $type,
                'price' => $price,
                'date' => $noteDate,
                'remark' => $remark,
            )
        );
        if (!$addResult) {
            returnJson(500, 508);
        }
    }

    /**
     * 编辑记一笔记录
     * @modify wenhui 2017-12-19 创建
     * @param  integer   $hotelId     客栈id
     * @param  integer   $noteCostId     记一笔条目id
     * @param  integer   $noteId     记一笔项目id
     * @param  integer   $payId     支付方式id
     * @param  integer   $type 记一笔记录类型  1=收入 2=支出
     * @param  decimal   $price 金额
     * @param  string   $noteDate 记一笔记录日期
     * @param  string   $remark 详情
     * @param  bool   $isDelete 是否删除
     */
    public function editNoteCost($hotelId, $noteCostId, $noteId, $payId, $type, $price, $noteDate, $remark, $isDelete) {
        //检查客栈是否已过期
        $this->checkHotelActive($hotelId);
        //检查客栈是否启用
        $this->checkHotelStatus($hotelId);

        $hotelNoteCostModel = D('HotelNoteCost');
        $saveResult = $hotelNoteCostModel->editNoteCost($hotelId, $noteCostId, $noteId, $payId, $type, $price, $noteDate, $remark, $isDelete);
        if (!$saveResult) {
            returnJson(500, 508);
        }
    }

    /**
     * 添加查房数据
     * @modify wenhui 2017-12-19 创建
     * @param  integer   $hotelId     客栈id
     * @param  string   $name 项目名称
     */
    public function setRoomCost($hotelId, $name) {
        //检查客栈是否已过期
        $this->checkHotelActive($hotelId);
        //检查客栈是否启用
        $this->checkHotelStatus($hotelId);

        $costInfos = $this->getCheckRoomCost($hotelId);
        if (count($costInfos) >= MAX_RESOURCE_COUNT) {
            returnJson(403, 406);
        }

        $costNames = array_column($costInfos, 'name');
        if (in_array($name, $costNames)) {
            returnJson(403, 430);
        }

        $hotelRoomCostModel = D('HotelRoomCost');
        $addResult = $hotelRoomCostModel->addInfo($hotelId, $name);
        if (!$addResult) {
            returnJson(500, 508);
        }

        return $addResult;
    }

    /**
     * 修改查房数据
     * @modify wenhui 2017-12-19 创建
     * @param  integer   $hotelId     客栈id
     * @param  string   $costId 物品id
     * @param  string   $name 名称
     */
    public function saveRoomCost($hotelId, $costId, $name) {
        //检查客栈是否已过期
        $this->checkHotelActive($hotelId);
        //检查客栈是否启用
        $this->checkHotelStatus($hotelId);

        $costInfos = $this->getCheckRoomCost($hotelId);
        $costInfos = getArrayValueAsIndex($costInfos, 'id');
        $hotelCostIds = array_column($costInfos, 'id');
        if (!in_array($costId, $hotelCostIds)) {
            returnJson(403, 202);
        }

        $hotelRoomCostModel = D('HotelRoomCost');
        $saveResult = $hotelRoomCostModel->saveInfo($hotelId, $costId, $name);
        if ($saveResult === false) {
            returnJson(500, 508);
        }

        return true;
    }

    /**
     * 删除查房数据
     * @modify wenhui 2017-12-19 创建
     * @param  integer   $hotelId     客栈id
     * @param  string   $costId 客栈记一笔id
     */
    public function deleteRoomCost($hotelId, $costId) {
        //检查客栈是否已过期
        $this->checkHotelActive($hotelId);
        //检查客栈是否启用
        $this->checkHotelStatus($hotelId);

        $costInfos = $this->getCheckRoomCost($hotelId);        
        $costInfos = getArrayValueAsIndex($costInfos, 'id');
        $hotelCostIds = array_column($costInfos, 'id');
        if (!in_array($costId, $hotelCostIds)) {
            returnJson(403, 202);
        }

        $hotelRoomCostModel = D('HotelRoomCost');
        $deleteResult = $hotelRoomCostModel->deleteCheckRoom($hotelId, $costId);
        if (empty($deleteResult)) {
            returnJson(500, 510);
        }
        return $deleteResult;
    }

    /**
     * 获取查房数据
     * @modify wenhui 2017-12-19 创建
     * @param  integer   $hotelId   客栈id
     * @param  boolean   $getDelete   是否包括已删除查房数据
     * @param  array   $data  返回数据
     */
    public function getCheckRoomCost($hotelId, $getDelete = false) {
        return $this->__singleGet('_getCheckRoomCost', array($hotelId, $getDelete));
    }
    protected function _getCheckRoomCost($hotelId, $getDelete = false) {
        $hotelRoomCostModel = D('HotelRoomCost');
        $data = $hotelRoomCostModel->getRoomCostInfoByHotel($hotelId);

        if ($getDelete !== true) {
            foreach ($data as $index => &$cost) {
                if ($cost['isdelete'] == IS_DELETE) {
                    unset($data[$index]);
                }
            }
            $data = array_values($data);
        }

        return $data;
    }

    /**
     * 保存客栈查房开关
     * 方法会抛异常
     * @modify wenhui 2017-12-19 创建
     * @param  integer   $hotelId     客栈id
     * @param  integer   $roomWard 0=关闭 1=开启
     */
    public function saveRoomCheck($hotelId, $roomWard) {
        $hotelEntityModel = D('HotelEntity');
        $saveResult = $hotelEntityModel->saveInfo($hotelId, null, null, null, null, null, null, null, $roomWard);
        if (empty($saveResult)) {
            throw new \Exception('500,506', 506);
            return false;
        }

        return $saveResult;
    }

    /**
     * 获取客栈查房开关
     * @modify wenhui 2017-12-19 创建
     * @param  integer   $hotelId     客栈id
     */
    public function getRoomCheck($hotelId) {
        $hotelEntityModel = D('HotelEntity');
        $data = $hotelEntityModel->getInfo($hotelId);

        $returnData = array(
            'type' =>  isset($data['roomward']) ? $data['roomward'] : 0, 
        );

        return $returnData;
    }
}
